# coding: utf-8
from io import BytesIO
from typing import Union

import requests
from PIL import Image
from PIL.ImageQt import toqimage
from PySide6.QtGui import QImage, QPixmap
from qfluentwidgets.common.image_utils import gaussianBlur
from requests import get

requests.packages.urllib3.disable_warnings()


class ImageHelper:
    """
    这个类用于处理图片相关的操作
    """

    @staticmethod
    def get_image_from_url(url: str, **kwargs) -> QImage:
        """
        从url获取图片
        :param url: 图片的url
        :return: 图片的二进制数据
        """
        response = get(url, verify=False, **kwargs)
        response.raise_for_status()
        file_bytes = BytesIO(response.content)
        img = Image.open(file_bytes)
        return toqimage(img)

    @staticmethod
    def get_image_from_file(file_path: str, width: int = 300) -> QImage:
        """
        从本地文件获取图片
        :param file_path: 图片的本地路径
        :param width: 图片的宽度
        :return: 图片的二进制数据
        """
        img = Image.open(file_path)
        h = int(width / img.width * img.height)
        img = img.resize((width, h))
        return toqimage(img)

    @staticmethod
    def download_image(url: str, file_path: str) -> bool:
        """
        下载图片到本地
        :param url: 图片的url
        :param file_path: 图片的本地路径
        :return: 是否下载成功
        """
        ImageHelper.get_image_from_url(url).save(file_path)
        return True


if __name__ == '__main__':
    href = "https://i0.hdslb.com/bfs/manga-static/2cd9cfdaf03c91157d26c5a5e572844bf026cbbf.jpg@310w.avif"
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0'
    }
    print(ImageHelper.get_image_from_url(href).isNull())
